<template>
  <div class="page" @keyup.enter="gotoPage()">
    <span>总共{{total}}条</span>
    <ul class="page-list">
      <li class="page-item" :class="{disabled: page <= 1}" @click="gotoPage(page - 1)">上一页</li>
      <template
        v-for="i in pageNum"
        >
        <li
          v-if="i === 1 || i === pageNum ||((i > page - groups) && (i < page + groups))"
          :key="i"
          class="page-item"
          :class="{active: page === i}"
          @click="gotoPage(i)"
          >{{i}}</li>
        <li
          v-else-if="(i === page - groups) || (i === page + groups)"
          :key="i"
          class="page-item no-page"
          >
          ...
        </li>
      </template>
      <li class="page-item" :class="{disabled: page >= pageNum}" @click="gotoPage(page + 1)">下一页</li>
    </ul>
    <div class="inline-block">
      跳转第
      <input class="input-page" type="text" v-model.number="goPage">
      页
      <button class="btn btn-sm" @click="gotoPage()">确认</button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    total: {
      type: Number,
      default: 0,
    },
    page: {
      type: Number,
      default: 1,
    },
    size: {
      type: Number,
      default: 10,
    },
    groups: {
      type: Number,
      default: 3,
    },
  },
  data() {
    return {
      goPage: 1,
    };
  },
  computed: {
    pageNum() {
      return Math.ceil(this.total / this.size);
    },
  },
  created() {
    this.goPage = this.page;
  },
  methods: {
    gotoPage(page = this.goPage) {
      const index = Math.max(1, Math.min(page, this.pageNum));
      this.goPage = index;
      this.$emit('update:page', index);
    }
  }
};
</script>

<style lang="less">
.page {
  user-select: none;
  .page-list {
    display: inline-block;
    margin: 0 10px;
  }
  .page-item {
    display: inline-block;
    padding: 0 8px;
    border-radius: 4px;
    border: 1px solid #ccc;
    font-size: 14px;
    margin: 0 5px;
    height: 30px;
    line-height: 30px;
    cursor: pointer;
    min-width: 30px;
    &.active {
      background-color: #ccc;
    }
    &:hover {
      background-color: #eee;
    }
    &.disabled {
      opacity: .5;
      cursor: not-allowed;
    }
    &.no-page {
      border: 0;
      cursor: default;
      &.active, &:hover {
        background-color: initial;
      }
    }
  }
  .input-page {
    width: 30px;
    display: inline-block;
  }
  .inline-block {
    display: inline-block;
  }
}
</style>
